package com.aiwhose.aiwhosewechatplublicaiwhose.utils.message;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.CustomMessageBean;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.FileMediaInfoBean;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.WXAiArticle;
import com.aiwhose.aiwhosecore.bean.plublicaiwhose.bean.WXAiMiniProgramBean;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.RedisUtil;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.WXPlubFileUtils;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.WXPlublicUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
@Component
public class WXMessageCustomerUtil {
    @Resource
    RedisUtil redisUtil;

    @Resource
    WXPlublicUtil wxPlublicUtil;
    @Resource
    WXPlubFileUtils wxPlubFileUtils;

    public boolean sendWXAiMessage(String openId, String content, String messageId) throws JsonProcessingException {
        JSONObject jsonObject = null;
        try {
            jsonObject = JSONUtil.parseObj(content);
        } catch (Exception e) {
            CustomMessageBean.TextMessage textMessage = new CustomMessageBean.TextMessage(openId, content);
            this.sendTextMessage(textMessage);
            return true;
        }
        Object image = jsonObject.get("image");
        if (ObjectUtil.isNotEmpty(image)) {
            JSONObject imageObject = JSONUtil.parseObj(image.toString());
            Object name = imageObject.get("name");
            String url = imageObject.get("url").toString();
            if (ObjectUtil.isNotEmpty(name)) {
                this.sendTextMessage(new CustomMessageBean.TextMessage(openId, name.toString()));
            }
            this.sendImageMessage(openId, url, null, messageId);
        }

        Object news = jsonObject.get("news");
        if (ObjectUtil.isNotEmpty(news)) {
            JSONArray articles = (JSONArray) JSONUtil.parseObj(news.toString()).get("articles");
            for (Object articleObj : articles) {
                WXAiArticle bean = BeanUtil.toBean(articleObj, WXAiArticle.class);
                CustomMessageBean.TextImageMessage.News.Article article = new CustomMessageBean.TextImageMessage.News.Article();
                article.setTitle(bean.getTitle());
                article.setUrl(bean.getUrl());
                article.setPicurl(bean.getPicurl());
                article.setDescription(bean.getDescription());
                CustomMessageBean.TextImageMessage.News news1 = new CustomMessageBean.TextImageMessage.News();
                ArrayList<CustomMessageBean.TextImageMessage.News.Article> articles1 = new ArrayList<>();
                articles1.add(article);
                news1.setArticles(articles1);
                CustomMessageBean.TextImageMessage textImageMessage = new CustomMessageBean.TextImageMessage(openId, news1);
                boolean b = this.sendTextImageMessage(textImageMessage);
            }

        }
        Object miniprogrampage = jsonObject.get("miniprogrampage");
        if (ObjectUtil.isNotEmpty(miniprogrampage)) {
            WXAiMiniProgramBean bean = BeanUtil.toBean(JSONUtil.parse(miniprogrampage.toString()), WXAiMiniProgramBean.class);
            String url = "<a href=\"" + bean.getThumb_url() + "\" data-miniprogram-appid=\"" + bean.getAppid() + "\" data-miniprogram-path=\"" + bean.getPagepath() + "\">" + bean.getTitle() + "</a>";
            CustomMessageBean.TextMessage textMessage = new CustomMessageBean.TextMessage(openId, url);
            sendTextMessage(textMessage);
        }
        return true;
    }


    /**
     * 发送文本消息
     *
     * @param textMessage 文本消息
     * @return 返回结果JSON
     */
    public boolean sendTextMessage(CustomMessageBean.TextMessage textMessage) throws JsonProcessingException {

//        CustomMessageBean.TextMessage textMessage = new CustomMessageBean.TextMessage(openId, content);
        String accessToken = wxPlublicUtil.getAccessToken();
        String jsonString = JSONUtil.toJsonStr(textMessage);
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken, jsonString);
        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(result);
        if ("ok".equals(entries.get("errmsg"))) {
            redisUtil.rSet("CustomTextMessage_" + textMessage.getTouser(), textMessage, 60 * 60 * 24 * 30);
            return true;
        }
        return false;
    }

    public boolean sendImageMessage(String userOpen, String fileUrl, String mediaId, String messageId) throws JsonProcessingException {
        String accessToken = wxPlublicUtil.getAccessToken();
        if (StrUtil.isBlank(mediaId)) {
            FileMediaInfoBean fileMediaId = wxPlubFileUtils.getFileMediaId(fileUrl);
            if (fileMediaId == null) {
                return false;
            }
            mediaId = fileMediaId.getMedia_id();
        }
        CustomMessageBean.ImageMessage imageMessage = new CustomMessageBean.ImageMessage(userOpen, mediaId);
        String jsonString = JSONUtil.toJsonStr(imageMessage);





        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken, jsonString);
        redisUtil.hset("MESSAGE_SEND_SUCCESS", messageId + fileUrl, messageId, 60 * 5);
        log.error(result);
        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(result);
        if ("ok".equals(entries.get("errmsg"))) {
            redisUtil.rSet("CustomImageMessage_" + imageMessage.getTouser(), imageMessage, 60 * 60 * 24 * 30);
            return true;
        }
        return false;
    }

    public boolean sendTextImageMessage(CustomMessageBean.TextImageMessage textImageMessage) throws JsonProcessingException {

        String accessToken = wxPlublicUtil.getAccessToken();
        String jsonString = JSONUtil.toJsonStr(textImageMessage);
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + accessToken, jsonString);
        cn.hutool.json.JSONObject entries = JSONUtil.parseObj(result);
        if ("ok".equals(entries.get("errmsg"))) {
            redisUtil.rSet("CustomTextMessage_" + textImageMessage.getTouser(), textImageMessage, 60 * 60 * 24 * 30);
            return true;
        }

        return true;
    }


    /**
     * 发送正在输入状态
     * @param touser
     * @param command "Typing"：对用户下发“正在输入"状态 "CancelTyping"：取消对用户的”正在输入"状态
     * @return
     * @throws JsonProcessingException
     */
    public boolean InputState(String touser,String command)  {

        String accessToken = wxPlublicUtil.getAccessToken();
        HashMap<String, String> map = new HashMap<>();
        map.put("touser", touser);
        map.put("command", command);
        String jsonString = JSONUtil.toJsonStr(map);
        String result = HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/custom/typing?access_token=" + accessToken, jsonString);
        return true;
    }
}
